package com.example.firstprojectnew.service;

import com.example.firstprojectnew.common.RedisKey;
import com.example.firstprojectnew.common.WrapMapper;
import com.example.firstprojectnew.common.Wrapper;
import com.example.firstprojectnew.entity.User;
import com.example.firstprojectnew.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lihua
 * @Date: 2025/3/21 14:29
 * @Version: v1.0.0
 * @Description:
 **/
@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<User> getAllUser(){
        List<User> userList = userMapper.getAllUser();
        return userList;
    }

    public void test(){
        this.testAsync();
    }


    @Async
    public void testAsync(){
        log.info("任务开始 ：" + LocalTime.now());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("任务结束：" + LocalTime.now());
    }


    public User getUserById(String id){
        String useKey = String.format(RedisKey.USER_INFO_KEY,id);
        User user = (User) redisTemplate.opsForValue().get(useKey);
        if(user == null){
            user = userMapper.getUserById(id);
            if(user == null ){
                log.error("id错误，无用户信息 {}" ,id);
            }else {
                log.info("用户信息从MySQL获取。");
                redisTemplate.opsForValue().set(useKey,user,30,TimeUnit.SECONDS);
            }
        }else {
            log.info("用户信息从Redis获取。");
        }
        return user;
    }

    public Wrapper updatePhone(String userId , String newPhone){
        User user = this.getUserById(userId);
        if(user == null){
            return WrapMapper.error("用户不存在");
        }else {
            user.setUserPhone(newPhone);
            userMapper.updatePhone(user);
            String useKey = String.format(RedisKey.USER_INFO_KEY,userId);
            redisTemplate.delete(useKey);
            return WrapMapper.ok("修改成功");
        }
    }

    public static void main(String[] args) {
        Random random = new Random();
        Set<Integer> nums = new LinkedHashSet<>();
        while (true){
            int num = random.nextInt(12)+1;
            nums.add(num);
            if (nums.size() == 12)
                break;
        }
        for (int num : nums){
            System.out.print( num + "  ");
        }
    }

}
